/**
 * LongTask长任务监控（严格监控≥50ms的任务）
 *
 */

import { ReportType } from './constant';
import { ReportParams } from './types';
import Utils from './utils';

export default class LongTask {
	private observer: PerformanceObserver | null = null;

	constructor(private callback: (params: ReportParams) => void) {
		Utils.log('LongTask监控初始化');
		this.initObserver();
	}

	/**
	 * 初始化性能观察者
	 */
	private initObserver() {
		if (!this.supportsPerformanceObserver()) {
			Utils.log('warn', '当前环境不支持PerformanceObserver');
			return;
		}

		try {
			this.observer = new PerformanceObserver(this.processEntries.bind(this));
			this.observer.observe({
				type: 'longtask',
				buffered: true, // 捕获已发生的长任务
			});
		} catch (e) {
			Utils.log('error', 'PerformanceObserver初始化异常', e);
		}
	}

	/**
	 * 处理性能条目
	 */
	private processEntries(list: PerformanceObserverEntryList) {
		list
			.getEntries()
			.filter(entry => entry.duration >= 50) // 严格过滤≥50ms的任务
			.forEach(entry => {
				this.callback(this.createReport(entry));
			});
	}

	/**
	 * 创建报告对象
	 */
	private createReport(entry: PerformanceEntry): ReportParams {
		return {
			type: ReportType.LONG_TASK,
			message: `LongTask detected: ${entry.duration.toFixed(1)}ms`,
			duration: entry.duration,
			startTime: entry.startTime,
			...this.getAttribution(entry),
		};
	}

	/**
	 * 获取任务来源信息
	 */
	private getAttribution(entry: any): object {
		const attr = entry.attribution?.[0] || {};
		return {
			containerType: attr.containerType,
			containerSrc: attr.containerSrc,
			containerId: attr.containerId,
			containerName: attr.containerName,
		};
	}

	/**
	 * 检查浏览器支持
	 */
	private supportsPerformanceObserver(): boolean {
		return (
			'PerformanceObserver' in window &&
			PerformanceObserver.supportedEntryTypes.includes('longtask')
		);
	}
}
